package com.jsz.peini.server.thread;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jsz.peini.bean.activity.ActivityInfo;
import com.jsz.peini.bean.task.TaskInfo;
import com.jsz.peini.bean.task.TaskInfoExample;
import com.jsz.peini.bean.user.UserInfo;
import com.jsz.peini.common.util.AppPush;
import com.jsz.peini.common.util.PeiniUtils;
import com.jsz.peini.common.util.SmsSendUtil;
import com.jsz.peini.common.util.SpringContextUtil;
import com.jsz.peini.mapper.activity.ActivityInfoMapper;
import com.jsz.peini.mapper.activity.ActivityUserMapper;
import com.jsz.peini.mapper.task.TaskInfoMapper;
import com.jsz.peini.mapper.user.UserInfoMapper;
import com.jsz.peini.mapper.user.UserSmsMapper;
import com.jsz.peini.redis.util.TaskRedisUtil;

@Component
public class TaskCancleThread {
	private static final Logger logger = LoggerFactory.getLogger(TaskCancleThread.class);
	public static boolean flag = false;
	public static Timer timer;
	
	@Resource
	private  ActivityInfoMapper activityInfoMapper;
	@Resource
	private  ActivityUserMapper activityUserMapper;
	@Resource
	private  UserInfoMapper userInfoMapper;
	@Resource
	private  UserSmsMapper userSmsMapper;
	
	public TaskCancleThread() {
		
	}
	
	public void init(){
		startTimer();
	}
	
	public static void stopTimer(){
		flag = false;
		timer.cancel();
	}
	public void startTimer(){
		flag = true;
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.HOUR_OF_DAY, 8);
		calendar.set(Calendar.MINUTE, 50);
		calendar.set(Calendar.SECOND, 0);
		final Date timerDate = calendar.getTime();

		timer = new Timer();

		//每10分钟取消已过期任务
		timer.schedule(new TimerTask(){
			@Override
			public void run() {
				logger.info("-----------------------------已过期任务自动清理中--------------------------------------------------");
				
				List<Integer> statusList = new ArrayList<Integer>();
				statusList.add(1);
				statusList.add(5);
				TaskInfoMapper taskInfoMapper = (TaskInfoMapper)SpringContextUtil.getBean(TaskInfoMapper.class);
				TaskInfoExample example = new TaskInfoExample();
				example.createCriteria().andTaskStatusIn(statusList).andTaskAppointedTimeLessThan(new Date());
				List<TaskInfo> list = taskInfoMapper.selectByExample(example);
				for (TaskInfo taskInfo : list) {
					if(taskInfo.getTaskStatus() == 1){
						TaskInfo info = new TaskInfo();
						info.setId(taskInfo.getId());
						info.setTaskStatus(5);
						info.setTaskCancleType(3);
						info.setTaskCancleTime(new Date());
						info.setCancelUserId(taskInfo.getUserId());
						taskInfoMapper.updateByPrimaryKeySelective(info);
						
						String userId = taskInfo.getUserId();
						UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
						int taskNum = userInfo.getTaskNum() == null ? 0 : userInfo.getTaskNum();
						if (taskNum-3 >= 1000) {
							userInfo.setTaskNum(1000);
						}else{
							userInfo.setTaskNum(taskNum-3);
						}
						userInfo.setReputation(PeiniUtils.getCredit(userInfo,1));
						userInfoMapper.updateByPrimaryKeySelective(userInfo);
						
						JSONObject object = new JSONObject();
						object.put("title", "任务自动取消通知");
						object.put("paramId", taskInfo.getId());
						object.put("type", 108);
				        object.put("content","由于您发布的“"+taskInfo.getSellerInfoName()+"”任务已超过任务时间仍未被接取，系统已为您自动取消并收回发任务时赠送的任务经验3分，不要气馁，让我们继续约起来~下一个可能更好哦");
				        UserInfo u1 = userInfoMapper.selectByPrimaryKey(taskInfo.getUserId());
						AppPush.sendPush(object,u1.getUserPhone().toString().split(","));
						
						SmsSendUtil.sendSmsNotify(taskInfo.getUserId(), taskInfo.getId().toString(), 108, "由于您发布的“"+taskInfo.getSellerInfoName()+"”任务已超过任务时间仍未被接取，系统已为您自动取消并收回发任务时赠送的任务经验3分，不要气馁，让我们继续约起来~下一个可能更好哦");
					}
					
					if(TaskRedisUtil.taskExist(taskInfo.getId().toString())){
						List<LinkedHashMap<String, Object>> taskList = taskInfoMapper.selectByALL(taskInfo);
						for (LinkedHashMap<String, Object> taskMap : taskList) {
							TaskRedisUtil.delTaskInfo(taskInfo.getId().toString());
						}
					}
				}
				
				Calendar calendar = Calendar.getInstance();
				calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH)-1);
				example = new TaskInfoExample();
				example.createCriteria().andTaskAppointedTimeLessThanOrEqualTo(calendar.getTime()).andTaskStatusLessThan(3).andTaskOtherStatusLessThan(31);
				list = taskInfoMapper.selectByExample(example);
				for (TaskInfo taskInfo : list) {
					TaskInfo info = new TaskInfo();
					info.setId(taskInfo.getId());
					info.setTaskStatus(5);
					info.setTaskOtherStatus(5);
					info.setTaskCancleType(3);
					info.setTaskCancleTime(new Date());
					taskInfoMapper.updateByPrimaryKeySelective(info);
					
					JSONObject object = new JSONObject();
					object.put("title", "任务自动取消通知");
					object.put("paramId", taskInfo.getId());
					object.put("type", 109);
			        object.put("content","由于您发布的“"+taskInfo.getSellerInfoName()+"”任务超过一天仍未有人付款，系统自动判定为任务失败并收回发任务时赠送的任务积分3分，不要气馁，让我们继续约起来~下一个可能更好哦");
			        UserInfo u1 = userInfoMapper.selectByPrimaryKey(taskInfo.getUserId());
					AppPush.sendPush(object,u1.getUserPhone().toString().split(","));
					
					SmsSendUtil.sendSmsNotify(taskInfo.getUserId(), taskInfo.getId().toString(), 109, "由于您发布的“"+taskInfo.getSellerInfoName()+"”任务超过一天仍未有人付款，系统自动判定为任务失败并收回发任务时赠送的任务积分3分，不要气馁，让我们继续约起来~下一个可能更好哦");
					
					object = new JSONObject();
					object.put("title", "任务自动取消通知");
					object.put("paramId", taskInfo.getId());
					object.put("type", 109);
			        object.put("content","由于您参加的“"+taskInfo.getSellerInfoName()+"”任务超过一天仍未有人付款，系统自动判定为任务失败，不要气馁，让我们继续约起来~下一个可能更好哦~");
			        UserInfo otherUser = userInfoMapper.selectByPrimaryKey(taskInfo.getOtherUserId());
					AppPush.sendPush(object,otherUser.getUserPhone().toString().split(","));
					
					SmsSendUtil.sendSmsNotify(taskInfo.getOtherUserId(), taskInfo.getId().toString(), 109, "由于您参加的“"+taskInfo.getSellerInfoName()+"”任务超过一天仍未有人付款，系统自动判定为任务失败，不要气馁，让我们继续约起来~下一个可能更好哦~");
				}
			}
			
		},2000,1000*60*10);
		
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				ActivityInfo activityInfo=new ActivityInfo();
				Date date=new Date();
				activityInfo.setSignStartTime(new Date(date.getTime()- Long.parseLong("1") *60*60 * 1000));
				activityInfo.setSignEndTime(date);
				List<ActivityInfo> activity=activityInfoMapper.getActivityInfoByWillStart(activityInfo);
				if (activity.size()>0) {
					for (int i = 0; i < activity.size(); i++) {
						Integer infonum=userInfoMapper.getUserInfoAllIdAndPhoneCount();
						if (activity.get(i).getAcTitle()!=null) {
							if (infonum>0) {
								int pagenum=infonum%1000==0?infonum/1000:infonum/1000+1;
								for (int j = 1; j <pagenum+1; j++) {
									Page<LinkedHashMap<String,Object>> page = PageHelper.startPage(j,1000);
									List<LinkedHashMap<String, Object>> userinfo=userInfoMapper.getUserInfoAllIdAndPhone();
									for (int n = 0; n < userinfo.size(); n++) {
										//消息推送
										JSONObject object = new JSONObject();
										object.put("title", "系统消息");
										object.put("content", "“"+activity.get(i).getAcTitle()+"”活动发布了！惊喜准备就绪，就等你来参与啦！");
										object.put("type", 115);
										AppPush.sendPush(object,userinfo.get(n).get("userPhone").toString().split(","));
										
										//给发起人推送消息										
										SmsSendUtil.sendSmsNotify(userinfo.get(n).get("id").toString(), activity.get(i).getAcId(), 115, "“"+activity.get(i).getAcTitle()+"”活动发布了！惊喜准备就绪，就等你来参与啦！");
									}
								}
							}
						}
					}
				}
			}
		},2000,1000*60);
		
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				ActivityInfo activityInfo=new ActivityInfo();
				Date date=new Date();
				activityInfo.setSignStartTime(new Date(date.getTime()- Long.parseLong("1") *60*60 * 1000));
				activityInfo.setSignEndTime(date);
				List<ActivityInfo> activity=activityInfoMapper.getActivityInfoByStart(activityInfo);
				if (activity.size()>0) {
					for (int i = 0; i < activity.size(); i++) {
						List<LinkedHashMap<String, Object>> userinfo=activityUserMapper.getUserInfoAllIdAndPhone();
						for (int n = 0; n < userinfo.size(); n++) {
							//消息推送
							JSONObject object = new JSONObject();
							object.put("title", "系统消息");
							object.put("content", "您参加的“"+activity.get(i).getAcTitle()+"”活动正式开启啦！快点去看看吧~");
							object.put("type", 115);
							AppPush.sendPush(object,userinfo.get(n).get("userPhone").toString().split(","));
							//给发起人推送消息
							/*UserSms newuserSms = new UserSms();
							newuserSms.setSmsid(UUID.randomUUID().toString().replace("-", ""));
							newuserSms.setIsremind(0);
							newuserSms.setReceivdel(0);
							newuserSms.setSenddel(0);
							newuserSms.setParamid(activity.get(i).getAcId());
							newuserSms.setSendtime(new Date());
							newuserSms.setSmscontent("您参加的“"+activity.get(i).getAcTitle()+"”活动正式开启啦！快点去看看吧~");
							newuserSms.setSmstype(115);
							newuserSms.setToid(userinfo.get(n).get("id").toString());
							userSmsMapper.insertSelective(newuserSms);*/
							SmsSendUtil.sendSmsNotify(userinfo.get(n).get("id").toString(), activity.get(i).getAcId(), 115, "您参加的“"+activity.get(i).getAcTitle()+"”活动正式开启啦！快点去看看吧~");
						}
					}
				}
			}
		},2000,1000*60*60);
		
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				ActivityInfo activityInfo=new ActivityInfo();
				Date date=new Date();
				activityInfo.setSignStartTime(new Date(date.getTime()- Long.parseLong("1") *60*60 * 1000));
				activityInfo.setSignEndTime(date);
				List<ActivityInfo> activity=activityInfoMapper.getActivityInfoByEnd(activityInfo);
				if (activity.size()>0) {
					for (int i = 0; i < activity.size(); i++) {
						List<LinkedHashMap<String, Object>> userinfo=activityUserMapper.getUserInfoAllIdAndPhone();
						for (int n = 0; n < userinfo.size(); n++) {
							//消息推送
							JSONObject object = new JSONObject();
							object.put("title", "系统消息");
							object.put("content", "您参加的“"+activity.get(i).getAcTitle()+"”活动已结束！感谢您的参与~惊喜不断，下次我还在这等你~");
							object.put("type", 115);
							AppPush.sendPush(object,userinfo.get(n).get("userPhone").toString().split(","));
														
							SmsSendUtil.sendSmsNotify(userinfo.get(n).get("id").toString(), activity.get(i).getAcId(), 115, "您参加的“"+activity.get(i).getAcTitle()+"”活动已结束！感谢您的参与~惊喜不断，下次我还在这等你~");
						}
					}
				}
			}
		},2000,1000*60*60);
	}
}
